<template>
    <el-card v-if="post" class="box-card">
        <template #header>
            <el-descriptions size="large">
                <template #title>
                    <h2>{{ post.title }}</h2>
                </template>
                <el-descriptions-item label="作者">{{post.author}}</el-descriptions-item>
                <el-descriptions-item label="更新日期">{{ new Date(post.updateTime).toLocaleString()}}</el-descriptions-item>
                <el-descriptions-item label="标签" label-align="center">
                    <el-tag v-for="(v,i) in tags" :key="i" style="margin-right: 5px">
                        {{ v }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="浏览" label-align="center">{{ newPost.looks}}</el-descriptions-item>
                <el-descriptions-item label="点赞">
                    <el-button text v-if="newPost.thumbFlag === 0" @click="thumb()">{{ newPost.thumbs }}</el-button>
                    <el-button type="primary" @click="thumb()" v-else>{{ newPost.thumbs }}</el-button>
                </el-descriptions-item>
                <el-descriptions-item label="收藏">
                    <el-button text v-if="newPost.collectFlag === 0" @click="collect()">{{
                        newPost.collects
                        }}
                    </el-button>
                    <el-button type="primary" @click="collect()" v-else>{{ newPost.collects }}</el-button>
                </el-descriptions-item>
            </el-descriptions>
        </template>
        <div v-html="post.content"/>
    </el-card>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {getAllNum, toCollect, toLook, toThumb} from "@/request/post";
import store from "@/store";

name = "PostDetailView";

window.scroll(0, 0);

const post = store.getters.getGlobalPost;

const newPost = ref({
    thumbs: post.thumbs,
    thumbFlag: 0,
    collects: post.collects,
    collectFlag: 0,
    looks: post.looks + 1
})

onMounted(()=>{
    getAllNum(post.postId).then(({data})=>{
        console.log("allNums",data)
        newPost.value = {
            ...data.data
        };
    })
})

toLook(post.postId).then(({data})=>{
    console.log(data);
})

const tags = computed(() => {
    return post.tags.split(" ");
})

const collect = () => {
    let flag = (newPost.value.collectFlag + 1) % 2;
    console.log("collect", flag);
    newPost.value.collectFlag = flag;
    newPost.value.collects += flag === 0 ? -1 : 1;
    toCollect(flag,post.postId).then(({data})=>{
        console.log(data)
    })
}

const thumb = () => {
    let flag = (newPost.value.thumbFlag + 1) % 2;
    console.log("thumb", flag);
    newPost.value.thumbFlag = flag;
    newPost.value.thumbs += flag === 0 ? -1 : 1;
    toThumb(flag,post.postId).then(({data})=>{
        console.log(data)
    })
}

</script>

<style scoped>

.box-card {
    width: 100%;
}
</style>
